import django_filters
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from django_filters.filterset import FilterSet
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets
from good import models, serializers
from rest_framework.decorators import action


# Create your views here.
class GoodPage(PageNumberPagination):
    page_size = 3
    page_size_query_param = 'size'


class GoodFilter(FilterSet):
    cate = django_filters.CharFilter(field_name='cate', lookup_expr='contains')

    class Meta:
        model = models.Good
        fields = ['cate']


class GoodView(viewsets.ModelViewSet):
    queryset = models.Good.objects.all()
    serializer_class = serializers.GoodSer
    filter_backends = [DjangoFilterBackend]
    filterset_class = GoodFilter
    pagination_class = GoodPage

    def create(self, request):
        try:
            ret = models.Good.objects.get(name=request.data['name'])
            print("$$$$$$$$$$")
            print(ret)
            if ret:
                print("判断重复")
                ret.number = ret.number + request.data.get("number")
                ret.save()
                print(request.data.get("number"))
                return Response({"msg": "数量修改成功", "status": 201})
            else:
                ser = self.get_serializer(data=request.data)
                if ser.is_valid():
                    ser.save()
                    return Response({"msg": "添加购物车成功", "status": 202})
                else:
                    return Response({"msg": "添加购物车失败", "status": 400, "error": ser.errors})
        except:
            print('%%%%%%%%%%')
            ser = self.get_serializer(data=request.data)
            print('@@@@@@@@@')
            if ser.is_valid():
                ser.save()
                return Response({"msg": "添加购物车成功", "status": 203})
            else:
                return Response({"msg": "添加购物车失败", "status": 400, "error": ser.errors})

class ShopView(viewsets.ModelViewSet):
    queryset = models.Shops.objects.all()
    serializer_class = serializers.ShopSer

